/*
 * @Author: 徐建辰
 * @Date: 2021-11-04 14:38:03
 * @LastEditTime: 2021-11-04 14:53:35
 * @LastEditors: Please set LastEditors
 * @Description: 搜索组件
 */
import React, {memo, useEffect, useState, useMemo} from 'react'
import PropTypes from 'prop-types'
import SearchItem from './SearchItem'
import './CitySelector.css'

const Search = memo(function Search(props) {
  const {searchKey, onSelect} = props
  const [result, setResult] = useState([])

  useEffect(() => {
    fetch('xxxxxx').then(res => res.json()).then(data => {
      const {result: tRes, searchKey: sKey} = data
      // 避免旧的搜索结果也显示出来，和当前的搜索结果不匹配
      sKey === searchKey && setResult(tRes)
      // if (sKey === searchKey) {
      //   setResult(result)
      // }
    })
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchKey])

  const fallBackResult = useMemo(() => result.length ? result : [{display: searchKey}], [result, searchKey])

  return (
    <div className="city-suggest">
      <ul className="city-suggest-ul">
        {fallBackResult.map(item => <SearchItem key={item.display} name={item.display} onClick={onSelect} />)}
      </ul>
    </div>
  )
})

Search.propTypes = {
  searchKey: PropTypes.string.isRequired,
  onSelect: PropTypes.func.isRequired,
}

export default Search
